package com.beerq.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Utility class of the application
 * Created by bhanu on 19/10/15.
 */
public class Utility {

    /**
     * Convert the array into list of CommonFields object
     *
     * @param options
     * @return
     */
//    public static List<CommonFields> getCommonFields(String[] options) {
//
//        List<CommonFields> commonFieldses = new ArrayList<>();
//        for (int i = 0; i < options.length; i++) {
//            CommonFields commonFields = new CommonFields();
//            commonFields.setId(String.valueOf(i + 1));
//            commonFields.setName(options[i]);
//            commonFieldses.add(commonFields);
//        }
//        return commonFieldses;
//    }



    /**
     * Check if there storing the request params will required the the database storage or not
     *
     * @param serviceName
     * @return
     */
    public static boolean requireStorage(String serviceName) {

        boolean status = false;
        switch (serviceName) {
//            case ApiUrlConstant.PROVIDER_LOGIN:
//                status = true;
//                break;
//            case ApiUrlConstant.JOB_DETAILS:
//                status = true;
//                break;


        }
        return status;
    }




//    public static void startHome(Activity activity, Class activityClass) {
//
//        Intent in = new Intent(activity, activityClass);
//        in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//        activity.startActivity(in);
//    }

    /**
     * Return the bitmap of and file
     *
     * @param filepath real path of file
     * @return
     */
    public static Bitmap decodeFile(String filepath) {
        if (filepath == null || filepath.isEmpty())
            return null;
        return decodeFile(new File(filepath));
    }


    /**
     * Return the bitmap of and file
     *
     * @param f File
     * @return
     */
    public static Bitmap decodeFile(File f) {
        if (!f.exists()) {
            Log.e("Step 2", "file not exist");
            return null;
        }
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);
            Log.e("Step 3", "Decoded");

            // The new size we want to scale to
            final int REQUIRED_SIZE = 200;

            // Find the correct scale value. It should be the power of 2.
            int scale = 1;
            while (o.outWidth / scale / 2 >= REQUIRED_SIZE &&
                    o.outHeight / scale / 2 >= REQUIRED_SIZE) {
                scale *= 2;
            }

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            Log.e("Step 4", "New file generated with resize");
            //return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
            return checkRotationAndGetBitmap(f.getAbsolutePath(), o2);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.e("Step 5", "Exception");
        }
        return null;
    }


    public static Bitmap checkRotationAndGetBitmap(String photoPath, BitmapFactory.Options o2) {
        ExifInterface ei = null;
        Bitmap bitmap = null;
        try {
            ei = new ExifInterface(photoPath);

            int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);

            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    bitmap = rotateImage(BitmapFactory.decodeStream(new FileInputStream(photoPath), null, o2), 90);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    bitmap = rotateImage(BitmapFactory.decodeStream(new FileInputStream(photoPath), null, o2), 180);
                    break;
                default:
                    bitmap = BitmapFactory.decodeStream(new FileInputStream(photoPath), null, o2);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    public static Bitmap rotateImage(Bitmap source, float angle) {
        Bitmap retVal;

        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        retVal = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);

        return retVal;
    }


    /**
     * Show dialog to take picture option and start activity for camera or gallery
     *
     * @param activity
     */

    public static void getPictureOnActivity(final Activity activity) {

        File file = new File(Constants.ROOT_DIR);
        if (!file.exists()) {
            file.mkdir();
        }
        final CharSequence[] items = {"拍照", "从画廊选择", "取消"};

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("添加照片！");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface Dialog, int item) {
                Dialog.dismiss();
                if (items[item].equals("拍照")) {
                    takePicFromCamera(activity, Constants.CAMERA_APP);
                   /* File file = new File(Constants.ROOT_DIR, "profileImage.jpg");
                    if (file.exists()) {
                        file.delete();
                    }
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                    activity.startActivityForResult(intent, Constants.REQUEST_CAMERA);*/
                } else if (items[item].equals("从画廊选择")) {
                    takePicFromGallery(activity);
                } else if (items[item].equals("取消")) {
                    Dialog.dismiss();
                }
            }
        });
        builder.show();
    }


    /**
     * Take picture from gallery
     *
     * @param activity
     */
    public static void takePicFromGallery(Activity activity) {
        Intent intent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        activity.startActivityForResult(Intent.createChooser(intent, "Select File"),Constants.GALLERY_APP);
    }

//    public static void takePicFromGallery(Fragment fragment) {
//        Intent intent = new Intent(Intent.ACTION_PICK,
//                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        intent.setType("image/*");
//        fragment.startActivityForResult(Intent.createChooser(intent, "Select File"),
//                Constants.GALLERY_APP);
//    }

    /**
     * Take picture from camera
     *
     * @param activity
     * @param requestCode
     */
    public static void takePicFromCamera(Activity activity, int requestCode) {
        File file = new File(Constants.ROOT_DIR + "/" + Constants.IMAGE_FOLDER_NAME);
        if (!file.exists()) {
            file.mkdir();
        }

        File picPath = new File(file.getPath(), "beerq" + "_status_" + System.currentTimeMillis() + ".jpg");
        Constants.mCamRequestedUri = Uri.fromFile(picPath);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Constants.mCamRequestedUri);
        activity.startActivityForResult(intent, requestCode);
    }

//    public static void takePicFromCamera(final Fragment fragment, int requestCode) {
//        File file = new File(Constants.ROOT_DIR);
//        if (!file.exists()) {
//            file.mkdir();
//        }
//
//        File picPath = new File(Constants.ROOT_DIR, fragment.getString(R.string.app_name) + "_status_" + System.currentTimeMillis() + ".jpg");
//        Constants.mCamRequestedUri = Uri.fromFile(picPath);
//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        intent.putExtra("android.intent.extras.CAMERA_FACING", 1);
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, Constants.mCamRequestedUri);
//        fragment.startActivityForResult(intent, requestCode);
//    }

    /**
     * Get real path from uri
     *
     * @param activity
     * @param contentUri
     * @return
     */
    public static String getRealPathFromURI(Activity activity, Uri contentUri) {
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            return contentUri.getPath();
        }
    }

//    public static void launchMap(Context context, double latitude, double longitude, String label) {
//        String uriBegin = "geo:" + latitude + "," + longitude;
//        String query = latitude + "," + longitude + "(" + label + ")";
//        String encodedQuery = Uri.encode(query);
//        String uriString = uriBegin + "?q=" + encodedQuery + "&z=16";
//        Uri uri = Uri.parse(uriString);
//        try {
//            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//            context.startActivity(intent);
//        } catch (Exception e) {
//            DialogUtils.showToast(context, context.getString(R.string.error_google_map));
//        }
//    }

    /**
     * Hide the soft keypad
     *
     * @param context
     */
    public static void hideKeyboardForce(Context context) {
        if (context != null && !((Activity) context).isFinishing()) {
            InputMethodManager im = (InputMethodManager) context.getApplicationContext().getSystemService(
                    Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(((Activity) context).getWindow().getDecorView().getWindowToken(), 0);
        }
    }

    /**
     * Open the dial pad with give number
     *
     * @param context
     * @param number
     */
    public static void dialNumber(Context context, String number) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + number));
        context.startActivity(intent);
    }

//    public static String getAddressFromLatLong(Context context, LatLng latLng) {
//
//        Geocoder geocoder = new Geocoder(context, Locale.getDefault());
//        Address addresses = null;
//        String add = "";
//        try {
//
//            addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1).get(0);
//            if (addresses != null)
//                add = addresses.getAddressLine(0) + addresses.getAddressLine(1);
//
//            // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return add;
//
//    }

//    public static void closeSoftInputKeyPad(@NonNull Context context, @NonNull View view) {
//        try {
//            if (context == null || view == null)
//                return;
//
//            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
//            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }


    /**
     * Save signature to a file.
     *
     * @param context
     * @param pictureBitmap
     * @return
     */
    public static String saveSignatureToImage(Context context, Bitmap pictureBitmap) {
        //String path = Environment.getExternalStorageDirectory().toString();
        String path = context.getCacheDir().toString();
        OutputStream fOut = null;
        File file = new File(path, "signature_" + SystemClock.currentThreadTimeMillis() + "_img" + ".jpg"); // the File to save to
        try {
            fOut = new FileOutputStream(file);

            //Bitmap pictureBitmap = getImageBitmap(myurl); // obtaining the Bitmap
            pictureBitmap.compress(Bitmap.CompressFormat.PNG, 90, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
            fOut.flush();
            fOut.close(); // do not forget to close the stream


            //MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return file.getAbsolutePath();

    }







    /**
     * Check wether given image view has any tag or not
     *
     * @param imageView
     * @return
     */
    public static boolean isImageViewEmpty(ImageView imageView) {
        if (imageView == null)
            return true;
        if (imageView.getTag() == null || imageView.getTag().toString().isEmpty()) {
            return true;
        }
        return false;

    }


    /**
     * Return the formated date
     *
     * @param year
     * @param monthOfYear
     * @param dayOfMonth
     * @return
     */
    public static String getFormattedDate(int year, int monthOfYear, int dayOfMonth) {
        Calendar calendar = Calendar.getInstance();
        //calendar.set(year,monthOfYear,dayOfMonth);
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, monthOfYear);
        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
        Log.e("date", sdf.format(calendar.getTimeInMillis()));
        return sdf.format(calendar.getTimeInMillis());

    }





//    public static void startCall(Activity activity, String number) {
//        if (number==null)
//            return;
//        String no = "tel:" + number.trim();
//        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(no));
//        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
//            // TODO: Consider calling
//            //    ActivityCompat#requestPermissions
//            // here to request the missing permissions, and then overriding
//            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//            //                                          int[] grantResults)
//            // to handle the case where the user grants the permission. See the documentation
//            // for ActivityCompat#requestPermissions for more details.
//            return;
//        }
//        activity.startActivity(callIntent);
//    }

    public static void showSettingsAlert(final Context mContext) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog
                .setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        mContext.startActivity(intent);
                    }
                });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        // Showing Alert Message
        alertDialog.show();
    }
}